/**
 * 机构塑像数据接口
 * 用于获取和处理支行相关的各类数据
 */

import { queuedFetch } from '../config/environment'

/**
 * 执行SQL查询
 * @param {string} sql - SQL语句
 * @param {string} logName - 日志名称
 * @returns {Promise<Array>} 查询结果
 */
const executeSQL = async (sql, logName = 'SQL查询') => {
  try {
    console.log(`[机构塑像] ${logName} SQL:`, sql)
    
    // 准备POST数据
    const requestParams = {
      jdbcName: 'amsedb',  // MySQL数据库
      sql: sql
    }
    
    const postData = new URLSearchParams()
    postData.append('jdbcName', requestParams.jdbcName)
    
    // URL编码 + Base64编码
    let encodedSql = encodeURIComponent(sql)
    encodedSql = btoa(encodedSql)
    requestParams.enc = encodedSql
    postData.append('enc', requestParams.enc)
    
    // 发送请求
    const response = await queuedFetch('/jdbcmgr.do', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: postData.toString()
    }, {
      name: logName,
      priority: 10
    })
    
    if (response && response.data && Array.isArray(response.data)) {
      console.log(`[机构塑像] ${logName} 成功，共 ${response.data.length} 条数据`)
      return response.data
    }
    
    console.warn(`[机构塑像] ${logName} 返回数据格式异常:`, response)
    return []
    
  } catch (err) {
    console.error(`[机构塑像] ${logName} 失败:`, err)
    throw err
  }
}

/**
 * 获取支行核心KPI数据
 * @param {string} orgNo - 机构号
 * @param {string} bussDate - 业务日期（可选）
 * @returns {Promise<Object>} KPI数据
 */
export const fetchBranchKPIs = async (orgNo, bussDate = null) => {
  try {
    console.log(`[机构塑像] 开始获取支行KPI数据，机构号: ${orgNo}`)
    
    // 构建SQL - 获取贷款余额、存款余额、不良贷款率、员工人数
    let sql = `
      SELECT 
        index_nm,
        index_value,
        buss_dt
      FROM audit_index_total
      WHERE org_no = '${orgNo}'
        AND index_nm IN ('各项贷款总额', '各项存款余额', '不良贷款率', '员工人数')
        AND ori = '指标结果表'
    `
    
    if (bussDate) {
      sql += ` AND buss_dt = '${bussDate}'`
    }
    
    sql += ` ORDER BY buss_dt DESC`
    
    const result = await executeSQL(sql, '支行KPI数据')
    
    if (result && result.length > 0) {
      // 按指标名称分组，取最新数据
      const kpiMap = {}
      result.forEach(row => {
        const indexNm = row.index_nm || row.INDEX_NM
        const indexValue = row.index_value || row.INDEX_VALUE
        const bussDt = row.buss_dt || row.BUSS_DT
        
        if (!kpiMap[indexNm]) {
          kpiMap[indexNm] = {
            value: parseFloat(indexValue),
            date: bussDt
          }
        }
      })
      
      return {
        loanBalance: kpiMap['各项贷款总额']?.value || 0,
        depositBalance: kpiMap['各项存款余额']?.value || 0,
        nplRatio: kpiMap['不良贷款率']?.value || 0,
        staffCount: kpiMap['员工人数']?.value || 0
      }
    }
    
    return null
    
  } catch (err) {
    console.error('[机构塑像] 获取支行KPI数据失败:', err)
    throw err
  }
}

/**
 * 获取支行贷款业务数据
 * @param {string} orgNo - 机构号
 * @returns {Promise<Object>} 贷款业务数据
 */
export const fetchBranchLoanData = async (orgNo) => {
  try {
    console.log(`[机构塑像] 开始获取支行贷款业务数据，机构号: ${orgNo}`)
    
    const sql = `
      SELECT 
        index_nm,
        index_value,
        buss_dt
      FROM audit_index_total
      WHERE org_no = '${orgNo}'
        AND (
          index_nm LIKE '%零售%贷款%'
          OR index_nm LIKE '%对公%贷款%'
          OR index_nm LIKE '%个人%贷款%'
          OR index_nm LIKE '%企业%贷款%'
        )
        AND ori = '指标结果表'
      ORDER BY buss_dt DESC
      LIMIT 20
    `
    
    const result = await executeSQL(sql, '支行贷款业务数据')
    
    return result || []
    
  } catch (err) {
    console.error('[机构塑像] 获取支行贷款业务数据失败:', err)
    throw err
  }
}

/**
 * 获取支行存款业务数据
 * @param {string} orgNo - 机构号
 * @returns {Promise<Object>} 存款业务数据
 */
export const fetchBranchDepositData = async (orgNo) => {
  try {
    console.log(`[机构塑像] 开始获取支行存款业务数据，机构号: ${orgNo}`)
    
    const sql = `
      SELECT 
        index_nm,
        index_value,
        buss_dt
      FROM audit_index_total
      WHERE org_no = '${orgNo}'
        AND (
          index_nm LIKE '%个人%存款%'
          OR index_nm LIKE '%对公%存款%'
          OR index_nm LIKE '%企业%存款%'
        )
        AND ori = '指标结果表'
      ORDER BY buss_dt DESC
      LIMIT 20
    `
    
    const result = await executeSQL(sql, '支行存款业务数据')
    
    return result || []
    
  } catch (err) {
    console.error('[机构塑像] 获取支行存款业务数据失败:', err)
    throw err
  }
}

/**
 * 获取支行风险指标数据
 * @param {string} orgNo - 机构号
 * @returns {Promise<Object>} 风险指标数据
 */
export const fetchBranchRiskData = async (orgNo) => {
  try {
    console.log(`[机构塑像] 开始获取支行风险指标数据，机构号: ${orgNo}`)
    
    const sql = `
      SELECT 
        index_nm,
        index_value,
        buss_dt
      FROM audit_index_total
      WHERE org_no = '${orgNo}'
        AND index_nm IN ('不良贷款率', '拨备覆盖率', '资本充足率', '不良贷款余额')
        AND ori = '指标结果表'
      ORDER BY buss_dt DESC
    `
    
    const result = await executeSQL(sql, '支行风险指标数据')
    
    return result || []
    
  } catch (err) {
    console.error('[机构塑像] 获取支行风险指标数据失败:', err)
    throw err
  }
}

/**
 * 获取支行人员结构数据
 * @param {string} orgNo - 机构号
 * @returns {Promise<Array>} 人员结构数据
 */
export const fetchBranchStaffData = async (orgNo) => {
  try {
    console.log(`[机构塑像] 开始获取支行人员结构数据，机构号: ${orgNo}`)
    
    const sql = `
      SELECT 
        index_nm,
        index_value,
        buss_dt
      FROM audit_index_total
      WHERE org_no = '${orgNo}'
        AND (
          index_nm LIKE '%客户经理%'
          OR index_nm LIKE '%柜员%'
          OR index_nm LIKE '%风控%'
          OR index_nm LIKE '%运营%'
          OR index_nm LIKE '%管理%'
          OR index_nm = '员工人数'
        )
        AND ori = '指标结果表'
      ORDER BY buss_dt DESC
    `
    
    const result = await executeSQL(sql, '支行人员结构数据')
    
    return result || []
    
  } catch (err) {
    console.error('[机构塑像] 获取支行人员结构数据失败:', err)
    throw err
  }
}

/**
 * 获取支行经营趋势数据（近12个月）
 * @param {string} orgNo - 机构号
 * @returns {Promise<Array>} 经营趋势数据
 */
export const fetchBranchTrendData = async (orgNo) => {
  try {
    console.log(`[机构塑像] 开始获取支行经营趋势数据，机构号: ${orgNo}`)
    
    const sql = `
      SELECT 
        index_nm,
        index_value,
        buss_dt
      FROM audit_index_total
      WHERE org_no = '${orgNo}'
        AND index_nm IN ('各项贷款总额', '各项存款余额', '不良贷款率')
        AND ori = '指标结果表'
      ORDER BY buss_dt DESC
      LIMIT 36
    `
    
    const result = await executeSQL(sql, '支行经营趋势数据')
    
    if (result && result.length > 0) {
      // 按日期和指标分组
      const trendMap = {}
      
      result.forEach(row => {
        const bussDt = row.buss_dt || row.BUSS_DT
        const indexNm = row.index_nm || row.INDEX_NM
        const indexValue = parseFloat(row.index_value || row.INDEX_VALUE)
        
        if (!trendMap[bussDt]) {
          trendMap[bussDt] = {}
        }
        
        trendMap[bussDt][indexNm] = indexValue
      })
      
      // 转换为数组并排序
      const trendData = Object.keys(trendMap)
        .sort()
        .slice(-12)  // 只取最近12个月
        .map(date => ({
          date,
          loanBalance: trendMap[date]['各项贷款总额'] || 0,
          depositBalance: trendMap[date]['各项存款余额'] || 0,
          nplRatio: trendMap[date]['不良贷款率'] || 0
        }))
      
      return trendData
    }
    
    return []
    
  } catch (err) {
    console.error('[机构塑像] 获取支行经营趋势数据失败:', err)
    throw err
  }
}

/**
 * 获取支行完整画像数据
 * @param {string} orgNo - 机构号
 * @returns {Promise<Object>} 完整的机构塑像数据
 */
export const fetchBranchProfileData = async (orgNo) => {
  try {
    console.log(`[机构塑像] 开始获取完整机构塑像数据，机构号: ${orgNo}`)
    
    // 并行获取所有数据
    const [kpis, loanData, depositData, riskData, staffData, trendData] = await Promise.all([
      fetchBranchKPIs(orgNo),
      fetchBranchLoanData(orgNo),
      fetchBranchDepositData(orgNo),
      fetchBranchRiskData(orgNo),
      fetchBranchStaffData(orgNo),
      fetchBranchTrendData(orgNo)
    ])
    
    console.log('[机构塑像] 完整机构塑像数据获取完成')
    
    return {
      kpis,
      loanData,
      depositData,
      riskData,
      staffData,
      trendData
    }
    
  } catch (err) {
    console.error('[机构塑像] 获取完整机构塑像数据失败:', err)
    throw err
  }
}

export default {
  fetchBranchKPIs,
  fetchBranchLoanData,
  fetchBranchDepositData,
  fetchBranchRiskData,
  fetchBranchStaffData,
  fetchBranchTrendData,
  fetchBranchProfileData
}

